/*
 * @lc app=leetcode.cn id=103 lang=typescript
 *
 * [103] 二叉树的锯齿形层序遍历
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function zigzagLevelOrder(root: TreeNode | null): number[][] {

    if (!root) {
        return []
    }
    const q: any = [];
    q.push(root)
    const res: any = [];
    let flag = true; // false是反着来
    while (q.length !== 0) {
        const size = q.length;
        res.push([]);
        for (let i = 0; i < size; i++) {
            const node = q.shift();
            if (flag) {
                res[res.length - 1].push(node.val)
            } else {
                res[res.length - 1].unshift(node.val)
            }
            if (node.left !== null) {
                q.push(node.left)
            }
            if (node.right !== null) {
                q.push(node.right)
            }
        }
        flag = !flag;
    }
    return res;
};

// @lc code=end

